package com.ruoyi.web.utils;

import com.ruoyi.web.core.config.AdminConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

import javax.mail.internet.MimeMessage;
import java.io.File;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @ClassName EmailUtils
 * @Description 邮件发送
 * @Author yangtao2
 * @Date 2022/5/7 14:23
 * @Version 1.0
 **/
@Slf4j
@Service
public class EmailSender {

	@Value("${spring.mail.logo}")
	private String logo;

	/**
	 * 邮件发送
	 * @param templateEnum 模板
	 * @param replace 变量替换
	 * @return
	 */
	public boolean send(EmailTemplateEnum templateEnum, Map<String,Object> replace) {
		try {
			MimeMessage mimeMessage = AdminConfig.getAdminConfig().getMailSender().createMimeMessage();
			MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
			helper.setFrom(AdminConfig.getAdminConfig().getEmailFrom(), "瑞念信后台管理系统");
			helper.setTo(templateEnum.getTos());
			helper.setSubject(templateEnum.getSub());
			//模板替换
			String template = templateEnum.getTemplate();
			helper.setText(processTemplate(template,replace), true);
			//添加logo
			FileSystemResource resource = new FileSystemResource(new File(logo));
			helper.addInline("image", resource);
			if(!AdminConfig.getAdminConfig().isProd()){
				//测试环境
				log.info("非生产环境,限制下发邮件,操作成功!");
				helper.setTo("yangtaoer@126.com");
			}
			AdminConfig.getAdminConfig().getMailSender().send(mimeMessage);
		}catch (Exception e){
			log.error("邮件发送失败:",e);
			return false;
		}
		log.info("邮件发送成功-------->" + templateEnum);
		return true;
	}


	/**
	 * 变量替换表达式
	 */
	private static final Pattern REPLACE_PATTERN = Pattern.compile("\\$\\{\\w+\\}");
	/**
	 * 模板替换
	 * @param template
	 * @param params
	 * @return
	 */
	private String processTemplate(String template, Map<String, Object> params) {
		StringBuffer sb = new StringBuffer();
		Matcher m = REPLACE_PATTERN.matcher(template);
		while (m.find()) {
			String param = m.group();
			Object value = params.get(param.substring(2, param.length() - 1));
			m.appendReplacement(sb, value == null ? "" : value.toString());
		}
		m.appendTail(sb);
		return sb.toString();
	}
}
